package com.imooc.controller;

import com.imooc.constants.RedisConstant;
import com.imooc.converter.ProductForm2ProductInfoConverter;
import com.imooc.dataobject.ProductCategory;
import com.imooc.dataobject.ProductInfo;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.form.ProductForm;
import com.imooc.form.group.Insert;
import com.imooc.form.group.Update;
import com.imooc.service.CategoryService;
import com.imooc.service.ProductService;
import com.imooc.utils.KeyUtil;
import com.imooc.utils.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * FileName: SellerProductController.java
 * Description: 卖家端商品controller
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/29
 */
@Controller
@Slf4j
@RequestMapping("/seller/product")
public class SellerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 商品列表
     * @param page
     * @param size
     * @param model
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "#{sellerConfig.page.size}") Integer size,
                             Map<String, Object> model) {
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        Page<ProductInfo> productInfoPage = this.productService.findAll(pageRequest);
        model.put("productInfoPage", productInfoPage);
        model.put("curPage", page);
        model.put("size", size);
        return new ModelAndView("/product/list", model);
    }

    /**
     * 修改/新增商品页面
     * @param productId
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "productId", required = false) String productId,
                              Map<String, Object> model) {
        ProductInfo productInfo;
        if (StringUtils.isBlank(productId)) {
            // 新增
            productInfo = new ProductInfo();
        } else {
            // 修改
            productInfo = this.productService.findOne(productId);
            if (null == productInfo) {
                log.error("【卖家端修改商品】查找不到商品productId={}", productId);
                return new ModelAndView("redirect:/seller/product/list");
            }
        }

        List<ProductCategory> productCategories = this.categoryService.findAll();

        model.put("productInfo", productInfo);
        model.put("productCategories", productCategories);
        return new ModelAndView("/product/index", model);
    }

    /**
     * 新增/更新商品内容
     * @param productForm
     * @return
     */
    @PostMapping("/save")
    // 缓存方式1-2
    @CacheEvict(cacheNames = RedisConstant.CACHE_BUYER_PRODUCT_UP_LIST, key = RedisConstant.KEY_BUYER_PRODUCT)
    public ModelAndView save(ProductForm productForm,
                             Map<String, Object> model) {
        String failUrl = "/sell/seller/product/index";
        String successUrl = "/sell/seller/product/list";
        if (StringUtils.isNotBlank(productForm.getProductId())) {
            failUrl += "?productId=" + productForm.getProductId();
            successUrl = failUrl;
        }
        try {
            if (StringUtils.isBlank(productForm.getProductId())) {
                ValidateUtil.validate(productForm, Insert.class);
            } else {
                ValidateUtil.validate(productForm, Update.class);
            }
        } catch (SellException e) {
            log.error("【卖家端保存商品】请求参数有误， productInfo={}", productForm);
            model.put("msg", e.getMessage());
            model.put("url", failUrl);
            return new ModelAndView("/common/error", model);
        }

        try {
            ProductInfo productInfo = ProductForm2ProductInfoConverter.convert(productForm);

            if (StringUtils.isBlank(productInfo.getProductId())) {
                productInfo.setProductId(KeyUtil.genUniqueKey());
            } else {
                ProductInfo productDB = this.productService.findOne(productForm.getProductId());
                productInfo.setProductStatus(productDB.getProductStatus());
            }
            this.productService.save(productInfo);
            model.put("buyer_product", productInfo.getProductName());
        } catch (Exception e) {
            model.put("msg", e.getMessage());
            model.put("url", failUrl);
            return new ModelAndView("/common/error", model);
        }

        model.put("msg", ResultEnum.PRODUCT_SAVE_SUCCESS.getMessage());
        model.put("url", successUrl);
        return new ModelAndView("/common/success", model);
    }

    /**
     * 商品下架
     * @param productId
     * @return
     */
    @GetMapping("/off_sale")
    public ModelAndView offSale(@RequestParam("productId") String productId,
                                Map<String, Object> model) {
        try {
            this.productService.offSale(productId);
        } catch (SellException e) {
            model.put("msg", e.getMessage());
            model.put("url", "/sell/seller/product/list");
            return new ModelAndView("/common/error", model);
        }

        model.put("msg", ResultEnum.PRODUCT_OFF_SALE_SUCCESS.getMessage());
        model.put("url", "/sell/seller/product/list");
        return new ModelAndView("/common/success", model);
    }

    /**
     * 商品上架
     * @param productId
     * @return
     */
    @GetMapping("/on_sale")
    public ModelAndView onSale(@RequestParam("productId") String productId,
                               Map<String, Object> model) {
        try {
            this.productService.onSale(productId);
        } catch (SellException e) {
            model.put("msg", e.getMessage());
            model.put("url", "/sell/seller/product/list");
            return new ModelAndView("/common/error", model);
        }

        model.put("msg", ResultEnum.PRODUCT_ON_SALE_SUCCESS.getMessage());
        model.put("url", "/sell/seller/product/list");
        return new ModelAndView("/common/success", model);
    }
}
